#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <sys/mman.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <fcntl.h>

#define SERVER_IP "10.1.1.60" //"127.0.0.1"
#define PORT 6679
#define BUFFERLENGTH 1<<16

int main()
{
  int socket_fd;
  int i;
  socket_fd=socket(AF_INET,SOCK_STREAM,0);

  struct sockaddr_in server_addr;
  memset(&server_addr,0,sizeof(server_addr));
  server_addr.sin_family=AF_INET;
  server_addr.sin_port=htons(PORT);
  server_addr.sin_addr.s_addr=inet_addr(SERVER_IP);
  memset(&(server_addr.sin_zero),0,8);

  int res =connect(socket_fd,(struct sockaddr *)&server_addr,sizeof(server_addr));
  printf("connect res is %d\n",res);
            
  char path[100];
  //  printf("please give the path of the photo\n");
  printf("Enter your File Name:\n");
  char input[100];
  gets(input);
  sprintf(path,"%s",input);

  char inputFileName[100];

  for(i = strlen(input);i >= 0;i--)
    {
      if(input[i] == '\\') 
        {
          int k = 0;
          for(i = i + 1;i <= strlen(input);i++)
            {
              inputFileName[k++] = input[i];
            }
          break;
        }
    }
  
  write(socket_fd,inputFileName,100);

  FILE *out=fopen(path,"r");
  //  sprintf(path,"%s",input);
  //  FILE *new=fopen(path,"w");
  usleep(1000);
  int nread;
  char buff[BUFFERLENGTH];
    int fd;
  void *adr;
  fd = open(path, O_RDONLY);
  struct stat s;// = (struct stat *)malloc(sizeof(struct stat));
  fstat(fd, &s); // i get the size
  write(socket_fd,&s.st_size,4);
  /*adr = mmap(NULL, (size_t)s.st_size, PROT_READ, MAP_SHARED, fd, 0); // i get the adress
  write(socket_fd, adr, s.st_size);
  */
  int fileLen = 0;
    while((nread=fread(buff,sizeof(char),BUFFERLENGTH,out))>0)
    {
      //      fwrite(buff,sizeof(char),nread,new);
      write(socket_fd,buff,nread);
      fileLen += nread;
      if(fileLen >= s.st_size)
        {
          break;
        }
    }
  close(socket_fd);
  return 0;
}
